<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      v-show="showSearch"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="姓名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入姓名"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="警号" prop="badgeNumber">
        <el-input
          v-model="queryParams.badgeNumber"
          placeholder="请输入警号"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >查询</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['communityInfo:police:add']"
          >添加社区民警信息</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="tableList" border>
      <el-table-column label="序号" type="index" align="center" width="70" />
      <el-table-column label="头像" align="center" prop="avatar">
        <template #default="scope">
          <el-avatar :size="50" :src="baseUrl + scope.row.avatar" />
        </template>
      </el-table-column>
      <el-table-column label="姓名" prop="userName" align="center" />
      <el-table-column label="警号" prop="badgeNumber" align="center" />
      <el-table-column label="职务" prop="position" align="center">
        <template #default="scope">
          <span>{{
            scope.row.position === "0"
              ? "所领导"
              : scope.row.position === "1"
              ? "民警"
              : scope.row.position === "2"
              ? "辅警"
              : ""
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属社区" prop="communityName" align="center">
        <template #default="scope">
          <span>{{
            scope.row.communityId == 0 ? "朝阳派出所" : scope.row.communityName
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" prop="phonenumber" align="center" />
      <el-table-column label="状态" prop="dutyStatus" align="center">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.dutyStatus == 0">在岗</el-tag>
          <el-tag type="success" v-if="scope.row.dutyStatus == 1"
            >在岗-外出</el-tag
          >
          <el-tag type="success" v-if="scope.row.dutyStatus == 2"
            >在岗-巡逻</el-tag
          >
          <el-tag type="warning" v-if="scope.row.dutyStatus == 3"
            >不在岗</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="创建日期" align="center" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="210"
      >
        <template #default="scope">
          
          <el-button
            link
            type="primary"
            text
            @click="mjewm(scope.row)"
            v-hasPermi="['communityInfo:police:detail']"
          >
            民警二维码
          </el-button>
          <el-button
            link
            type="primary"
            text
            @click="handleDetail(scope.row)"
            v-hasPermi="['communityInfo:police:detail']"
          >
            查询
          </el-button>

          <el-button
            link
            type="primary"
            text
            @click="handleUpdate(scope.row)"
            v-hasPermi="['communityInfo:police:edit']"
          >
            编辑
          </el-button>

          <el-button
            link
            type="primary"
            text
            @click="handleDelete(scope.row)"
            v-hasPermi="['communityInfo:police:remove']"
          >
            删除
          </el-button>

          <el-button
            link
            type="primary"
            text
            @click="handleClock(scope.row)"
            v-hasPermi="['communityInfo:police:clock']"
          >
            打卡记录
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="35vw"
      align-center
      append-to-body
    >
      <el-form ref="policeRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="userName" required>
              <el-input
                v-model="form.userName"
                placeholder="请输入姓名"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="警号" prop="badgeNumber" required>
              <el-input
                v-model="form.badgeNumber"
                placeholder="请输入警号"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="职务" prop="position" required>
              <el-select
                v-model="form.position"
                placeholder="请选择"
                clearable
                style="width: 240px"
                @change="positionChange"
              >
                <el-option
                  v-for="dict in police_job"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属社区" prop="communityId" required>
              <el-select
                v-model="form.communityId"
                placeholder="请选择"
                clearable
                style="width: 240px"
              >
                <template v-if="form.position == 0">
                  <el-option
                    v-for="dict in unit_options"
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.id"
                  />
                </template>
                <template v-else>
                  <el-option
                    v-for="dict in community_options"
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.id"
                  />
                </template>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phonenumber" required>
              <el-input
                v-model="form.phonenumber"
                placeholder="请输入手机号"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="头像" prop="avatar" required>
              <image-upload
                v-model="form.avatar"
                :isShowTip="false"
                :limit="1"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">保 存</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      title="社区民警信息"
      v-model="openDetail"
      width="35vw"
      align-center
      append-to-body
    >
      <el-form ref="detailRef" :model="form" :rules="rules" label-width="90px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名：">{{ form.userName }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="警号：">{{ form.badgeNumber }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职务：">{{
              form.position === "0"
                ? "所领导"
                : form.position === "1"
                ? "民警"
                : form.position === "2"
                ? "辅警"
                : ""
            }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属社区：">{{
              form.communityId == 0 ? "朝阳派出所" : form.communityName
            }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态：">
              <el-tag type="success" v-if="form.dutyStatus == 0">在岗</el-tag>
              <el-tag type="success" v-if="form.dutyStatus == 1"
                >在岗-外出</el-tag
              >
              <el-tag type="success" v-if="form.dutyStatus == 2"
                >在岗-巡逻</el-tag
              >
              <el-tag type="warning" v-if="form.dutyStatus == 3">不在岗</el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号：">{{ form.phonenumber }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="头像：">
              <el-image
                style="width: 100px; height: 100px"
                :src="baseUrl + form.avatar"
                :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                :preview-src-list="[baseUrl + form.avatar]"
                :initial-index="0"
                fit="cover"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDetail">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 打卡记录对话框 -->
    <el-dialog
      title="民警打卡记录"
      v-model="openCalendar"
      width="35vw"
      align-center
      append-to-body
    >
      <el-calendar ref="calendar" :model-value="new Date(clockQuery.month)">
        <template #header="{ date }">
          <span>{{ date }}</span>
          <el-button-group>
            <el-button @click="selectDate('prev-month')">
              <el-icon :size="20" color="#409efc" class=""
                ><ArrowLeftBold
              /></el-icon>
            </el-button>
            <el-button @click="selectDate('next-month')">
              <el-icon :size="20" color="#409efc" class=""
                ><ArrowRightBold
              /></el-icon>
            </el-button>
          </el-button-group>
        </template>
        <template #date-cell="{ data }">
          <div class="content" @click="onDay(data.day)">
            <div
              :class="data.isSelected ? 'is-selected' : ''"
              style="text-align: center"
            >
              {{ data.day.split("-").slice(2).join("") }}
            </div>
            <div
              v-for="(item, index) in textContent(data.day)"
              :key="index"
              class="tag"
            >
              <div
                :class="
                  item.clockStatus === 1 && item.reportStatus === 1
                    ? 'type-1 type-2'
                    : item.clockStatus === 0 && item.reportStatus === 1
                    ? 'type-2'
                    : item.clockStatus === 1 && item.reportStatus === 0
                    ? 'type-1'
                    : ''
                "
              ></div>
            </div>
          </div>
        </template>
      </el-calendar>
      <div class="desc-text">
        <p @click="getClockList1()">
          本月打卡：<span>{{ clockRecord.clockMonthDayCount }}</span
          >天，<span>{{ clockRecord.clockMonthCount }}</span
          >次
        </p>
        <p @click="getReportList()">
          本月报备：<span>{{ clockRecord.reportMonthCount }}</span
          >次
        </p>
        <div>
          标记说明：
          <div>
            <div class="circle" style="background: #038afe"></div>
            <span>打卡</span>
          </div>
          <div>
            <div class="circle" style="background: #f9af2f"></div>
            <span>报备</span>
          </div>
        </div>
      </div>
    </el-dialog>

    <!--打卡信息对话框 -->
    <el-dialog
      title="打卡信息"
      v-model="openClock"
      width="35vw"
      align-center
      append-to-body
    >
      <div class="list-container">
        <template v-if="clockList.length">
          <div
            class="list-item"
            v-for="(item, index) in clockList"
            :key="index"
          >
            <p>
              <span>打卡时间：</span>
              <span>{{ parseTime(item.clockTime) }}</span>
              <span style="padding-left: 20px">打卡成功</span>
            </p>
          </div>
          <p>
            <span>打卡次数：</span>
            <span>{{ clockTotal }}</span>
          </p>
        </template>
        <el-empty v-else description="暂无记录" />
      </div>
      <div class="list-pagination">
        <pagination
          v-show="clockTotal > 0"
          :total="clockTotal"
          v-model:page="clockQuery1.pageNum"
          v-model:limit="clockQuery1.pageSize"
          @pagination="getClockList1"
        />
      </div>
    </el-dialog>

    <!--报备信息对话框 -->
    <el-dialog
      title="报备信息"
      v-model="openReport"
      width="35vw"
      align-center
      append-to-body
    >
      <div class="list-container">
        <template v-if="recordList.length">
          <div
            class="list-item"
            v-for="(item, index) in recordList"
            :key="index"
          >
            <p>
              <span>报备日期：</span>
              <span>{{
                parseTime(item.reportStartTime) +
                " 至 " +
                parseTime(item.reportEndTime)
              }}</span>
            </p>
            <p>
              <span>报备内容：</span>
              <span>{{ item.reportContent }}</span>
            </p>
            <p>
              <span>报备人：</span>
              <span>{{ item.policeUserName }}</span>
            </p>
            <p>
              <span>提交时间：</span>
              <span>{{ parseTime(item.createTime) }}</span>
            </p>
          </div>
        </template>
        <el-empty v-else description="暂无记录" />
      </div>
      <div class="list-pagination">
        <pagination
          v-show="reportTotal > 0"
          :total="reportTotal"
          v-model:page="reportQuery.pageNum"
          v-model:limit="reportQuery.pageSize"
          @pagination="getReportList"
        />
      </div>
    </el-dialog>


    
    <el-dialog
      title="民警二维码"
      v-model="flg"
      width="380"
      align-center
      append-to-body
    >
    <div style="text-align: center;">
      <img :src="'data:image/png;base64,' + ewmurl" alt="Base64 Image"/>
    </div>
    
      <!-- <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDetail">关 闭</el-button>
        </div>
      </template> -->
    </el-dialog>
  </div>
</template>

<script setup name="Police">
import {
  listPolice,
  addPolice,
  updatePolice,
  getPoliceById,
  delPolice,
  getClockList,
  listReport,
  listClock,
} from "@/api/community/police";
import { getCommunity } from "@/api/community/community";
import { dayjs } from "element-plus";

const { proxy } = getCurrentInstance();

const tableList = ref([]);
const open = ref(false);
const openDetail = ref(false);
const openCalendar = ref(false);
const openReport = ref(false);
const openClock = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const calendar = ref(null);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const community_options = ref([]);
const police_job = [
  {
    value: "0",
    label: "所领导",
  },
  {
    value: "1",
    label: "民警",
  },
  {
    value: "2",
    label: "辅警",
  },
];

const unit_options = ref([
  {
    id: 0,
    name: "朝阳派出所",
  },
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    badgeNumber: undefined,
    userName: undefined,
  },
  rules: {
    userName: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
    badgeNumber: [{ required: true, message: "警号不能为空", trigger: "blur" }],
    position: [{ required: true, message: "职务不能为空", trigger: "blur" }],
    communityId: [
      { required: true, message: "所属社区不能为空", trigger: "blur" },
    ],
    phonenumber: [
      { required: true, message: "手机号不能为空", trigger: "blur" },
      {
        pattern: /^1[3456789]\d{9}$/,
        message: "请输入正确的手机号格式",
        trigger: "blur",
      },
    ],
    avatar: [{ required: true, message: "头像不能为空", trigger: "blur" }],
  },
  clockQuery: {
    month: dayjs(new Date()).format("YYYY-MM"),
    policeUserId: undefined,
  },
  clockRecord: [],
  reportQuery: {
    pageNum: 1,
    pageSize: 10,
  },
  reportTotal: 0,
  clockList: [],
  clockQuery1: {
    pageNum: 1,
    pageSize: 10,
  },
  clockTotal: 0,
  recordList: [],
});

const {
  queryParams,
  form,
  rules,
  clockQuery,
  clockRecord,
  clockList,
  recordList,
  reportQuery,
  reportTotal,
  clockQuery1,
  clockTotal,
} = toRefs(data);

/** 查询列表 */
function getList() {
  loading.value = true;
  listPolice(queryParams.value).then((response) => {
    const { data } = response;
    tableList.value = data.records;
    total.value = data.total;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row) {
  const policeId = row.policeUserId;
  proxy.$modal
    .confirm("确认删除该数据？", "删除确认")
    .then(function () {
      return delPolice(policeId);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    policeUserId: undefined,
    userName: undefined,
    badgeNumber: undefined,
    position: undefined,
    communityId: undefined,
    phonenumber: undefined,
    avatar: undefined,
  };
  proxy.resetForm("policeRef");
}

/** 查询社区下拉列表数据 */
function getCommunityList() {
  getCommunity({}).then((response) => {
    const { data } = response;
    community_options.value = data;
  });
}

/** 添加 */
function handleAdd() {
  reset();
  getCommunityList();
  open.value = true;
  title.value = "添加社区民警信息";
}

/** 查询按钮操作 */
function handleDetail(row) {
  const policeId = row.policeUserId;
  getPoliceById({ id: policeId }).then((response) => {
    form.value = response.data;
    openDetail.value = true;
  });
}




const ewmurl = ref('');
const flg = ref(false);
function mjewm(e){
  ewmurl.value = e.qrCode
  flg.value = true
}

/** 修改 */
function handleUpdate(row) {
  reset();
  getCommunityList();
  const policeId = row.policeUserId;
  getPoliceById({ id: policeId }).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "社区民警信息编辑";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["policeRef"].validate((valid) => {
    if (valid) {
      if (form.value.policeUserId != undefined) {
        updatePolice(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPolice(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 关闭按钮 */
function closeDetail() {
  openDetail.value = false;
  reset();
}

/** 打卡记录 */
function handleClock(row) {
  clockQuery.value.policeUserId = row.policeUserId;
  getClockList(clockQuery.value).then((response) => {
    const { data } = response;
    clockRecord.value = data;
    openCalendar.value = true;
    clockQuery.value.month = dayjs(new Date()).format("YYYY-MM");
  });
}

function selectDate(val) {
  if (!calendar.value) return;
  calendar.value.selectDate(val);
  if (val === "prev-month") {
    clockQuery.value.month = dayjs(clockQuery.value.month)
      .add(-1, "month")
      .format("YYYY-MM");
  }
  if (val === "next-month") {
    clockQuery.value.month = dayjs(clockQuery.value.month)
      .add(1, "month")
      .format("YYYY-MM");
  }
  getClockList(clockQuery.value).then((response) => {
    const { data } = response;
    clockRecord.value = data;
    openCalendar.value = true;
  });
}

function onDay(date) {
  clockQuery.value.month = dayjs(date).format("YYYY-MM");
}

function textContent(date) {
  //当前date是拿到上面日历组件当前的日期值 根据该值去筛选测试数据找到对应各个日期下对应的数据return出去
  return clockRecord.value.monthVos.filter((item) => {
    return date == item.clockDay;
  });
}

/** 报备记录列表 */
function getReportList() {
  listReport({ ...reportQuery.value, ...clockQuery.value }).then((response) => {
    const { data } = response;
    recordList.value = data.records ?? [];
    reportTotal.value = data.total;
    openReport.value = true;
  });
}

/** 打卡记录列表 */
function getClockList1() {
  listClock({ ...clockQuery1.value, ...clockQuery.value }).then((response) => {
    const { data } = response;
    clockList.value = data.records ?? [];
    clockTotal.value = data.total;
    openClock.value = true;
  });
}

/** 所选职务改变事件 */
function positionChange(val) {
  if (val == 0) {
    form.value.communityId = 0;
  } else {
    form.value.communityId = undefined;
  }
}

getList();
</script>

<style lang="scss" scoped>
.list-container {
  height: 80vh;
  overflow: auto;
  max-height: 80vh;
  .list-item {
    margin-bottom: 10px;
    border-bottom: 1px solid #ccc;
  }
  .list-item:last-child {
    border-bottom: none;
    margin-bottom: 0;
  }
}

.list-pagination {
  margin-top: -30px;
  :deep(.pagination-container .el-pagination) {
    right: 20px !important;
  }
}

.desc-text {
  margin-bottom: 20px;
  p {
    cursor: pointer;
  }
  span {
    color: #038afe;
    padding: 0 5px;
  }
  div {
    display: flex;
    flex-direction: row;
    align-items: center;
  }
  .circle {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    margin-left: 8px;
  }
}
.content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.tag {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: end;
}
.type-1 {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #038afe;
}
.type-2 {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #f9af2f;
}
</style>
